package com.example.demo.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Random;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    Producer captchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/vc.jpg")
    public void image(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        response.setContentType("image/jpeg");
        String text = captchaProducer.createText();
        //有redis存在Redis中没有现存session
        session.setAttribute("kaptcha",text);
        BufferedImage image = captchaProducer.createImage(text);
        ImageIO.write(image, "jpg", response.getOutputStream());
    }
    @RequestMapping("/sendSms")
    public void sendSms(HttpSession session,@RequestBody String body) {
        String code = RandomUtil.randomNumbers(4);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String phone = jsonObject.getStr("phone");
        session.setAttribute(phone,code);
        log.info("手机号：{}，验证码为：{}",phone,code);
    }
}
